package com.qf.dao.impl;

import com.qf.dao.AddressDao;
import com.qf.domain.Address;
import com.qf.utils.DataSourceUtil;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import javax.sql.DataSource;
import java.sql.SQLException;
import java.util.List;

public class AddressDaoiImpl implements AddressDao {
    private QueryRunner queryRunner = new QueryRunner(DataSourceUtil.getDataSource());
    @Override
    public List<Address> select(Integer uid) {
        String sql = " select * from tb_address where uid=? ";
        try {
            return queryRunner.query(sql,new BeanListHandler<>(Address.class),uid);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void insert(Address address) {
        String sql = " insert into tb_address (detail,name,phone,uid,level) values (?,?,?,?,?) ";
        Object[] params = {address.getDetail(),address.getName(),address.getPhone(),address.getUid(),address.getLevel()};
        try {
            queryRunner.update(sql,params);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void delete(Integer uid, int aid) {
        String sql = " delete from tb_address where uid=? and id=? ";
        try {
            queryRunner.update(sql,uid,aid);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void updateLevel(Integer uid, int aid) {
        //当一个用户的地址设为默认地址后，该用户其他地址设置为普通地址
        try {
            queryRunner.update("update tb_address set level=0 where uid=?",uid);//先根据用户id将对应的用户地址都设置为普通地址
            queryRunner.update("update tb_address set level=1 where id=? and uid=?",aid,uid);//再根据用户id和地址id找到具体的一个地址设置为默认地址
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }

    }

    @Override
    public void update(Address address) {
        String sql = " update tb_address set detail=?,name=?,phone=?,level=? where id=? and uid=?  ";
        Object[] params = {address.getDetail(),address.getName(),address.getPhone(),address.getLevel(),address.getId(),address.getUid()};
        try {
            queryRunner.update(sql,params);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }
}
